var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})
var express = require('express')
var db = require('./db.js')
var router = express.Router()
var md5 = require("md5-node")

// router.post("/login", urlencodedParser, async function (req, res) {
//     var { loginName, loginKey } = req.body
//     var sql = `select id,name,gender,loginName,roles,status,avatar from users where loginName='${loginName}' and loginKey='${loginKey}'`
//     var data = await db.doMysql(sql)
//     res.send(db.postText(data))
// })

// 登录
router.post('/login', urlencodedParser, async function (req, res) {
    // 无token之前
    // var { loginName, loginKey } = req.body
    // var sql = "select id,name,gender,loginName,roles,status,avatar from users where loginName=? and loginKey=?"
    // const r = await db.doMysql(sql, [loginName, loginKey])
    // res.send(db.handerResult(r.data))
    // 有token
    var {
        loginName,
        loginKey
    } = req.body
    var sql = "select id,name,gender,loginName,roles,status,avatar from users where loginName=? and loginKey=?"
    const r = await db.doMysql(sql, [loginName, loginKey])
    // console.log(r[0].id)
    // console.log(r)
    // 判断用户名与密码是否匹配->if匹配,将id传给token
    if (r[0]) {
        // 将id传给token
        const token = await tokenFn(r[0].id)
        // 用户在登录时先判断有没token，没有则不能登录
        // console.log(token)
        if (token) {
            r[0].token = token
            // console.log(r.data[0])
            res.send(db.postText(r[0]))
        } else {
            // ...
        }
    } else {
        res.send(db.postText())
    }
})
/// 退出
router.post('/logout', urlencodedParser, async function (req, res) {
    // let { token } = req.body
    // // console.log(token)
    // let sql = "delete from tokens where token=?"
    // let r = await db.doMysql(sql, [token])
    // console.log(r)
    // if (r.affectedRows == 0) {
    //     res.send(db.errFn({}))
    // } else {
    //     res.send(db.postText({}))
    // }

    const {
        token
    } = req.body
    // console.log(token);
    // console.log(db.sfp,999);

    // res.send(db.handerdata({}))
    var sql = `delete from tokens where token = ('${token}')`
    const r = await db.doMysql(sql)
    console.log(r);
    if (r.affectedRows === 1) {
        res.send(db.postText(r))
    }

    // var {
    //     id
    // } = req.body
    // var sql = `delete from tokens where uid in (${id});`
    // const r = await db.doSQL(sql)
    // if (r.data.affectedRows === 1) {
    //     res.send(db.handerdata(r.data[0]))
    // }
})
// token
async function tokenFn(uid) {
    // 查询token数据表
    var sql = "select * from tokens where uid=?"
    const res = await db.doMysql(sql, [uid])
    // console.log(res)
    let token;
    // 判断有无token-->如果无,生成新token,有的话直接等于原来的token
    if (res.length == 0) {
        // 无token时
        // 生成32位字符串
        let newToken = md5('zxwx' + uid + Date.now())
        // 新增token
        const sql = "insert into tokens (token,uid) values (?,?)"
        const data = await db.doMysql(sql, [newToken, uid])
        // 判断token是否新增成功
        console.log(data)
        if (data.affectedRows == 1) {
            token = newToken
        } else {
            token = null
        }
    } else {
        // 有token时
        token = res[0].token
    }
    return token
}

router.get('/info', async function (req, res) {
    var {
        token
    } = req.query
    // console.log(token)
    var sql = `select u.id, roles, avatar, introduction,email,name from tokens as t, users as u where t.uid = u.id and t.token = '${token}'; `
    const r = await db.doMysql(sql)
    // console.log(r)
    if (r[0]) {
        res.send(db.backText(r[0]))
    } else {
        res.send(db.backText())
    }
})

module.exports = router;